package com.changgou.order.controller;

import com.changgou.entity.Result;
import com.changgou.order.feign.CartFeign;
import com.changgou.order.feign.OrderFeign;
import com.changgou.order.pojo.Order;
import com.changgou.order.pojo.OrderItem;
import com.changgou.user.feign.AddressFeign;
import com.changgou.user.pojo.Address;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/worder")
public class WebOrderController {

    @Autowired
    private AddressFeign addressFeign;

    @Autowired
    private CartFeign cartFeign;

    @RequestMapping("/ready/order")
    public String order(Model model){

        //获取地址列表
        Result<List<Address>> addressResult = addressFeign.list();
        List<Address> addressList = addressResult.getData();
        System.out.println("address : "+addressList);
        model.addAttribute("address",addressList);

        //获取购物车列表
        Map map = cartFeign.list();
        List<OrderItem> orderItemList = (List<OrderItem>) map.get("orderItemList");
        System.out.println("carts : "+orderItemList);

        Integer totalNum = (Integer) map.get("totalNum");
        Integer totalPrice = (Integer) map.get("totalPrice");

        model.addAttribute("carts",orderItemList);
        model.addAttribute("totalNum",totalNum);
        model.addAttribute("totalPrice",totalPrice);

        for (Address address : addressList) {
            if("1".equals(address.getIsDefault())){
                model.addAttribute("deAddr",address);
            }
        }

        //跳转到order.html页面
        return "order";
    }


    @Autowired
    private OrderFeign orderFeign;

    @PostMapping("/add")
    @ResponseBody
    public Result add(@RequestBody Order order){
        //通过feign进行远程调用,新增订单数据
        Result<String> result = orderFeign.add(order);
        return result;
    }

    @GetMapping("/toPayPage")
    public String toPayPage(String orderId,Model model){
        //支付页面需要orderId和支付金额
        //通过feign去进行获取,支付金额
        Result<Order> result = orderFeign.findById(orderId);
        Integer payMoney = result.getData().getPayMoney();
        model.addAttribute("orderId",orderId);
        model.addAttribute("payMoney",payMoney);
        return "pay";
    }

}
